//
//  LoginViewController.m
//  孕妙
//
//  Created by 是源科技 on 16/4/12.
//  Copyright © 2016年 是源科技. All rights reserved.
//

#import "LoginViewController.h"
#import "RegiesterViewController.h"
#import "HomeViewController.h"
#import "AssistantViewController.h"
#import "ShoppingViewController.h"
#import "ConsultingViewController.h"
#import "ForgetPassWordViewController.h"


@interface LoginViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *uesrNameTF;
@property (weak, nonatomic) IBOutlet UITextField *passwTF;
@property (weak, nonatomic) IBOutlet UIButton *savePWbtn;

@property (weak, nonatomic) IBOutlet UIButton *registerBtn;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;
//保存密码按钮标示
@property (nonatomic,assign)BOOL saveFlag;
//网络标志位
@property (nonatomic,assign)BOOL netFlag;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = YMColor(242, 242, 242);
    self.title = @"登录";
    
    //设置按钮圆角
    self.registerBtn.layer.cornerRadius = 8.0;
    self.loginBtn.layer.cornerRadius = 8.0;
    self.passwTF.secureTextEntry = YES;

    self.uesrNameTF.textColor = YMColor(102, 102, 102);
    self.passwTF.textColor = YMColor(102, 102, 102);
    
    self.uesrNameTF.keyboardType = UIKeyboardTypeDecimalPad;
    
   
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self netWorkingJianCe];
    self.tabBarController.tabBar.hidden = YES;
    [MobClick beginLogPageView:@"登录页面"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"登录页面"];
}
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSString *userAccount = [[NSUserDefaults standardUserDefaults]objectForKey:@"userAccount"];
    NSString *saveFlag = [[NSUserDefaults standardUserDefaults]objectForKey:@"saveFlag"];
    NSString *passWord = [[NSUserDefaults standardUserDefaults]objectForKey:@"userPassWord"];
    self.uesrNameTF.text = userAccount;
    
    if([saveFlag isEqualToString:@"isSave"] && userAccount != nil)
    {
        self.passwTF.text = passWord;
        [self autioLoginAccount:userAccount andPassword:passWord];
        self.saveFlag = YES;
        [self.savePWbtn setImage:[UIImage imageNamed:@"dl_Selected"] forState:UIControlStateNormal];
    }
}

-(void)netWorkingJianCe
{
    // 1.获得网络监控的管理者
    AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager];
    
    // 2.设置网络状态改变后的处理
    [mgr setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 当网络状态改变了, 就会调用这个block
        switch (status) {
            case AFNetworkReachabilityStatusUnknown: // 未知网络
                break;
                
            case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
                [MBProgressHUD showError:@"亲，网络连了吗？"];
                self.netFlag = NO;
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
                [MBProgressHUD showSuccess:@"手机自带网络"];
                self.netFlag = YES;
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
                [MBProgressHUD showSuccess:@"wifi"];
                self.netFlag = YES;
                break;
        }
    }];
    
    // 3.开始监控
    [mgr startMonitoring];//这里开始监控了才会回调上面的Block
    //    mgr.isReachable//检查是否有网络
    //    mgr.isReachableViaWiFi
    //    mgr.isReachableViaWWAN
}

//让键盘放弃第一响应者
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.uesrNameTF resignFirstResponder];
    [self.passwTF resignFirstResponder];
}

//记住密码
- (IBAction)savePWBtn:(id)sender
{
    if(self.saveFlag)
    {
        [self.savePWbtn setImage:[UIImage imageNamed:@"dl_Unselected"] forState:UIControlStateNormal];
        self.saveFlag = NO;
    }
    else
    {
         [self.savePWbtn setImage:[UIImage imageNamed:@"dl_Selected"] forState:UIControlStateNormal];
        self.saveFlag = YES;
    }
}

//忘记密码
- (IBAction)forgetPWBtn:(id)sender
{
    ForgetPassWordViewController *forgetPW = [[ForgetPassWordViewController alloc]init];
    [self.navigationController pushViewController:forgetPW animated:YES];
}
//注册按钮
- (IBAction)registerBtn:(id)sender
{
    RegiesterViewController *regiester = [[RegiesterViewController alloc]init];
    [self.navigationController pushViewController:regiester animated:YES];
}
//登录按钮
- (IBAction)loginBtn:(id)sender
{
    [self autioLoginAccount:self.uesrNameTF.text andPassword:self.passwTF.text];
    if(self.netFlag == NO)
    {
        [MBProgressHUD showError:@"亲，网络连了吗？"];
    }
}

-(void)autioLoginAccount:(NSString *)account andPassword:(NSString *)passWord
{
//    [MBProgressHUD showMessage:@"正在拼命加载，请稍后..."];
    NSString *urlString = @"http://120.24.178.16:8080/Health/baby/login.do";
    NSURL *url = [[NSURL alloc]initWithString:urlString];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2];
    
    request.HTTPMethod = @"POST";
    NSString *str = [NSString stringWithFormat:@"account=%@&devNo=0&password=%@",account,passWord];
    
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:data];
    
    NSOperationQueue *queue = [NSOperationQueue mainQueue];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        
        if (data)
        {
//            [MBProgressHUD hideHUD];
            // 请求成功
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
//            YMLog(@"dict = %@",dict);
            if([[dict objectForKey:@"code"] isEqualToString:@"0"])
            {
                if(self.saveFlag == 1)
                {
                    [[NSUserDefaults standardUserDefaults]setObject:@"isSave" forKey:@"saveFlag"];//自动登录
                }
                else
                {
                    [[NSUserDefaults standardUserDefaults]setObject:@"notSave" forKey:@"saveFlag"];
                }
                [[NSUserDefaults standardUserDefaults]setObject:self.uesrNameTF.text forKey:@"userAccount"];//保存账号
                [[NSUserDefaults standardUserDefaults]setObject:self.passwTF.text forKey:@"userPassWord"];//保存密码
                [MobClick profileSignInWithPUID:self.uesrNameTF.text];//友盟帐号统计
                [MBProgressHUD showSuccess:@"登录成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    AppDelegate *appde = (AppDelegate *)[UIApplication sharedApplication].delegate;
                    UIWindow *window = appde.window;
                    HomeViewController *home = [[HomeViewController alloc]init];
                    AssistantViewController *assistan = [[AssistantViewController alloc]init];
                    ShoppingViewController *shop = [[ShoppingViewController alloc]init];
                    ConsultingViewController *consult = [[ConsultingViewController alloc]init];
                    
                    sayesTabbarViewController *sayesN = [[sayesTabbarViewController alloc]init];
                    [sayesN addOneChlildVc:home title:@"首页" imageName:@"main_01" selectedImageName:@"main_02"];
                    [sayesN addOneChlildVc:assistan title:@"孕期助手" imageName:@"assistant_01" selectedImageName:@"assistant_02"];
                    [sayesN addOneChlildVc:shop title:@"商城" imageName:@"buy_01" selectedImageName:@"buy_02"];
                    [sayesN addOneChlildVc:consult title:@"咨询" imageName:@"chat_01" selectedImageName:@"chat_02"];
                    window.rootViewController = sayesN;
                });
                
            }
            else
            {
                [MBProgressHUD showError:[dict objectForKey:@"message"]];
            }
        }
    }];

}


@end
 